from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.schemas.calculator import CalculatorRequest, CalculatorResponse
from app.models.price_rule import PriceRule
from app.models.system_config import SystemConfig
from decimal import Decimal
import json

router = APIRouter()

@router.post("", response_model=CalculatorResponse)
def calculate_price(request: CalculatorRequest, db: Session = Depends(get_db)):
    rule = db.query(PriceRule).filter(
        PriceRule.apartment_type == request.apartment_type,
        PriceRule.area_min <= request.area,
        PriceRule.area_max >= request.area,
        PriceRule.is_active == True
    ).first()
    
    if not rule:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="未找到适用的造价规则"
        )
    
    unit_price = rule.unit_price
    base_cost = unit_price * request.area
    
    member_discount = Decimal("0")
    if request.is_member:
        config = db.query(SystemConfig).filter(
            SystemConfig.config_key == "member_discount"
        ).first()
        if config:
            member_discount = Decimal(config.config_value)
    
    final_cost = base_cost - member_discount
    
    config_items_config = db.query(SystemConfig).filter(
        SystemConfig.config_key == f"configuration_{request.apartment_type}"
    ).first()
    
    configuration_items = []
    if config_items_config:
        try:
            configuration_items = json.loads(config_items_config.config_value)
        except:
            pass
    
    return CalculatorResponse(
        apartment_type=request.apartment_type,
        area=request.area,
        unit_price=unit_price,
        base_cost=base_cost,
        member_discount=member_discount,
        final_cost=final_cost,
        configuration_items=configuration_items
    )

